<template>
    <div class="add-goods-container">
        <el-card class="form-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <span>新增商品</span>
              <el-button type="primary" @click="goBack">返回列表</el-button>
            </div>
          </template>
    
          <el-form ref="goodsForm" :model="form" :rules="rules" label-width="120px" label-position="left">
            <!-- 商品名称 -->
            <el-form-item label="商品名称" prop="name">
              <el-input v-model="form.name" placeholder="请输入商品名称" clearable/>
            </el-form-item>
    
            <!-- 商品价格 -->
            <el-form-item label="价格" prop="price">
              <el-input-number v-model="form.price" :min="0.0" :precision="2" :step="0.0" controls-position="right"/>
              <span class="unit">元</span>
            </el-form-item>
    
            <!-- 推荐语 -->
            <el-form-item label="推荐语" prop="recommend">
              <el-input v-model="form.recommend" type="textarea" :rows="3" placeholder="请输入商品推荐语" maxlength="100" show-word-limit/>
            </el-form-item>
  
            <el-form-item>
              <el-button type="primary" @click="submitForm">立即创建</el-button>
              <el-button @click="resetForm">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
  </template>
    
  <script setup>
    import { ref, reactive } from 'vue'
    import { ElMessage } from 'element-plus'
    import { useRouter } from 'vue-router'
    import { useStore } from 'vuex'
    import * as contract from '../../test/Truffle-ABI.js'
    import axios from 'axios';
      
    const router = useRouter()
    const store = useStore()
    const userid = store.state.user.uid
      
    // 表单数据
    const form = reactive({
      name: '',
      price: 0.0,
      recommend: ''
    })
      
    // 验证规则
    const rules = reactive({
      name: [
        { required: true, message: '请输入商品名称', trigger: 'blur' },
        { min: 2, max: 30, message: '长度在 2 到 30 个字符', trigger: 'blur' }
      ],
      price: [
        { required: true, message: '请输入商品价格', trigger: 'blur' }
        ],
      endTime: [
        { required: true, message: '请选择下架时间', trigger: 'change' }
        ]
    })
  
    // 表单提交
    const submitForm = async () => {
      try {
        await contract.initWeb3()
        const txReceipt = await contract.addUserGoods(userid,form.price*100)
        // 从收据中解析事件参数
        const event = txReceipt.events.ProductAdded
        const productId = event.returnValues.productId
        // 验证ID有效性
        if (!productId) {
          throw new Error('未能获取有效的区块链商品ID');
        }
        const shopData = {
          id: Number(productId), // 使用区块链ID
          name: form.name,
          recommend: form.recommend
        };
        await axios.post('http://localhost:3001/api/data', shopData)
        ElMessage.success(`商品创建成功！区块链ID: ${productId}`)
  
        store.commit('setTxt','个人主页')
        router.push('/userInit')
      } catch (error) {
          ElMessage.error(`创建失败: ${error.message}`)
          console.error('完整错误日志:', error)
      }
    }
      
      // 表单重置
    const resetForm = () => {
      form.name = ''
      form.price = 0.0
      form.recommend = ''
    }
      
    // 返回列表
    const goBack = () => {
      store.commit('setTxt','个人主页')
      router.push('/userInit')
    }
  </script>
    
  <style scoped>
    .add-goods-container {
      padding: 200px;
    }
    
    .form-card {
      max-width: 800px;
      margin: 0 auto;
    }
    
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
    
    .unit {
      margin-left: 10px;
      color: #666;
    }
  </style>